package com.ming.reggie.service.impl;

import com.ming.reggie.entity.ShoppingCart;
import com.ming.reggie.mapper.ShoppingCartMapper;
import com.ming.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    /**
     * 添加购物车方法
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        ShoppingCart dbCart = shoppingCartMapper.findByShoppingCart(shoppingCart);

        if(dbCart!=null){
            //如果有,数量+1,更新数量
            dbCart.setNumber(dbCart.getNumber()+1);
            shoppingCartMapper.updateNumber(dbCart.getId(),dbCart.getNumber());
        }else {
            //如果没有,新增一条购物车记录
            dbCart = shoppingCart;

            dbCart.setCreateTime(LocalDateTime.now());
            dbCart.setNumber(1);

            shoppingCartMapper.save(dbCart);
        }
        return dbCart;
    }

    /**
     * 查询指定用户的购物车集合数据
     *
     * @param UserId
     * @return
     */
    @Override
    public List<ShoppingCart> findAllByUserId(Long UserId) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findAllByUserId(UserId);
        return shoppingCartList;
    }

    /**
     * 清空购物车
     *
     * @param userId
     * @return
     */
    @Override
    public Integer clean(Long userId) {
        return shoppingCartMapper.deleteByUserId(userId);
    }
}
